<template>
  <div class="app-container">
    <!-- 搜索栏开始 -->
    <el-card class="box-card">
      <el-form ref="page" :inline="true" :model="page" size="small" label-width="90px">
        <el-form-item label="用户名">
          <el-input v-model="page.username" clearable placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="page.nickName" clearable placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="page.status" clearable placeholder="请选择启用状态">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item style="display: block;text-align: center;margin-top: 5px;">
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button type="warning" icon="el-icon-refresh" @click="reset()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 搜索栏结束 -->
    <!-- 操作按钮组 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPer="['sys:user:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPer="['sys:user:update']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate(null)"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPer="['sys:user:delete']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 操作按钮组结束 -->
    <!-- 数据表格开始 -->
    <div>
      <el-table v-loading="loading" :data="dataPage.rows" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" prop="username" label="账号" />
        <el-table-column align="center" prop="nickName" label="昵称" />
        <el-table-column align="center" prop="email" label="邮箱" />
        <el-table-column align="center" prop="header" label="头像">
          <template slot-scope="{row}">
            <el-image
              style="width: 50px; height: 50px"
              :src="row.header"
              fit="fill"
              :preview-src-list="[row.header]"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createTime" label="创建时间" />
        <el-table-column align="center" prop="updateTime" label="更新时间" />
        <el-table-column align="center" prop="loginTime" label="登录时间" />
        <el-table-column align="center" prop="status" label="启用状态">
          <template slot-scope="{row}">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(row)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="note" label="备注" />
        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <el-button type="text" icon="el-icon-document" @click="toInfo(row.id)">详情</el-button>
            <el-dropdown class="handle-button">
              <span class="el-dropdown-link">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-hasPer="['sys:user:update']">
                  <el-button type="text" icon="el-icon-edit" @click="handleUpdate(row.id)">修改</el-button>
                </el-dropdown-item>
                <el-dropdown-item v-hasPer="['sys:user:delete']">
                  <el-button type="text" icon="el-icon-delete" @click.native="handleDelete(row)">删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件开始 -->
    <div class="pageable">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="page.pageNum"
        :limit.sync="page.pageSize"
        @pagination="getByPage"
      />
    </div>
    <!-- 分页组件结束 -->
    <!-- 添加用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialog"
      width="650px"
      append-to-body
    >
      <sysUserAdd v-if="addDialog" @after="getByPage" @close="closeDialog" />
    </el-dialog>
    <!-- 添加用户弹窗结束 -->
    <!-- 修改弹窗 -->
    <el-dialog
      title="修改用户"
      :visible.sync="updateDialog"
      width="650px"
      append-to-body
    >
      <sysUserUpdate v-if="updateDialog" :active-id="activeId" @after="getByPage" @close="closeDialog" />
    </el-dialog>
    <!-- 修改弹窗结束 -->
    <!-- 详情弹窗开始 -->
    <el-dialog
      title="用户详情"
      :visible.sync="infoDialog"
      width="650px"
      append-to-body
    >
      <sysUserInfo :active-id="activeId" />
    </el-dialog>
    <!-- 详情弹窗结束 -->
  </div>
</template>

<script>
import sysUserApi from '@/api/system/sys-user'
import sysUserAdd from './sys-user-add'
import sysUserUpdate from './sys-user-update'
import sysUserInfo from './sys-user-info'
import { MessageBox } from 'element-ui'
import store from '@/store'
import Cookies from 'js-cookie'

export default {
  nane: 'sysuser',
  components: {
    sysUserAdd,
    sysUserUpdate,
    sysUserInfo
  },
  data() {
    return {
      // 加载层
      loading: false,
      // 分页对象
      page: {
        // 分页传参
        params: {},
        pageNum: 1,
        pageSize: 10
      },
      // 当前点击的用户
      activeId: '',
      // 控制添加用户弹窗展示
      addDialog: false,
      // 控制修改用户弹窗展示
      updateDialog: false,
      // 控制用户详情弹窗展示
      infoDialog: false,
      // 数据 page 对象
      dataPage: {},
      // 总记录数
      total: 0,
      // 选中的数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 日期范围
      dateRange: []
    }
  },
  created() {
    this.getByPage()
  },
  methods: {
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 分页查询
    getByPage() {
      this.loading = true
      sysUserApi.list(this.addDateRange(this.page, this.dateRange)).then(res => {
        this.dataPage = res
        this.total = res.total
        this.loading = false
      })
    },
    // 搜索
    search() {
      // 搜索时，要还原为第一页
      this.page.pageNum = 1
      this.getByPage()
    },
    // 弹出添加弹窗
    handleAdd() {
      this.addDialog = true
    },
    // 打开修改弹窗
    handleUpdate(id) {
      this.activeId = id || this.ids[0]
      this.updateDialog = true
    },
    // 查看用户详情
    toInfo(id) {
      this.activeId = id
      this.infoDialog = true
    },
    // 关闭弹窗
    closeDialog() {
      this.addDialog = false
      this.updateDialog = false
      this.infoDialog = false
      this.activeId = null
    },
    // 根据id删除
    handleDelete(row) {
      const ids = row.id || this.ids
      // 判断删除的是否是当前用户
      const id = this.$store.getters.user.id
      // 记录选中的ID/删除
      this.$confirm('是否删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        sysUserApi.delete(ids).then(res => {
          this.$message.success(res.msg)
          this.getByPage()
          // 判断删除的是否是当前用户
          if (ids.indexOf(id) !== -1) {
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
            ).then(() => {
              Cookies.remove('Authorization')
              Cookies.remove('username')
              Cookies.remove('password')
              store.dispatch('user/logout').then(() => {
                location.href = '/'
              })
            })
          }
        })
      })
    },
    // 改变页面开关触发
    changeStatus(row) {
      const status = row.status
      // 判断禁用的是否是当前用户
      const id = this.$store.getters.user.id
      if (status === 0) {
        // 禁用
        this.$confirm('是否禁用该用户，禁用后将无法登陆?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sysUserApi.enabled(row.id, 0).then(res => {
            this.$message.success(res.msg)
            this.getByPage()
            if (row.id.indexOf(id) !== -1) {
              MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
              }
              ).then(() => {
                Cookies.remove('Authorization')
                Cookies.remove('username')
                Cookies.remove('password')
                store.dispatch('user/logout').then(() => {
                  location.href = '/'
                })
              })
            }
          })
        }).catch(() => {
          row.status = 1
        })
      } else {
        // 启用
        this.$confirm('是否启用该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          sysUserApi.enabled(row.id, 1).then(res => {
            this.$message.success(res.msg)
            this.getByPage()
          })
        }).catch(() => {
          row.status = 0
        })
      }
    },
    // 表单重置
    reset() {
      this.page = {
        // 分页传参
        params: {},
        pageNum: this.page.pageNum,
        pageSize: this.page.pageSize
      }
      this.dateRange = []
      this.getByPage()
    }
  }
}
</script>

<style scoped>
.button-group {
  margin-bottom: 15px;
}

.pageable {
  margin-top: 15px;
}
</style>
<style>
.yby-table-header th {
  background: #ffffff;
  color: #000000;
}
</style>
